package com.example.shopping.controller.user;

import com.example.shopping.pojo.User;
import com.example.shopping.pojo.result.Result;
import com.example.shopping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 用户登录 controller层 接口实现
 * @author 瓶盖
 */
@Controller
@RequestMapping("/user.do")
public class UserController {
    /**
     * 用户的业务接口实现
     */
    @Autowired
    private UserService userService;

    /**
     * 登录操作
     * @param  account 账号
     * @param  password 密码
     * @return Result 消息结果集
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestParam("account") String account, @RequestParam("password") String password, HttpSession Session){
        User user = userService.login(account, password);
        if(user != null){
            Session.setAttribute("user",user);
            return Result.success(user);
        }else {
//            Session.setAttribute("user",null);
            return Result.fail(404,"账号或者密码错误？");
        }
    }

    /**
     * 用户 注册的接口
     *
     * @param user 用户对象
     * @return  Result 消息结果集
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User user) {
        int register = userService.register(user);
        if(register != 0){
            return Result.success("注册成功");
        }
        return Result.fail(500,"用户注册失败，账号已经存在");
    }
    @PutMapping("/addBalance")
    @ResponseBody
    public Result addBalance(@RequestParam("userId") int userId,@RequestParam("balance") int balance){
        boolean b = userService.addBalance(userId, balance);
        if (b){
            return Result.success("充值成功！！！");
        } else {
            return Result.fail(500,"充值失败！！！");
        }
    }

    /**
     * 暂时只能 传入 userId 获取 用户信息
     * @param model 消息集
     * @return Result 消息结果集
     */
    @PostMapping("/selectUser")
    @ResponseBody
    public Result selectUser(Model model){
        Object userId =  model.getAttribute("userId");
        if (userId == null) {
            return Result.fail("没有传入userId！");
        }
        User user = userService.selectUserById((int)userId);
        if (user == null) {
            return Result.fail("没有找到用户！");
        }
        return Result.success(user);
    }
}
